import { _decorator, Component, Node, Prefab } from 'cc';
import { BaseView } from '../../../../scripts/libs/rxjs/cc3/BaseView';
import { EditorStageView } from './EditorStageView';
import { gm } from '../../../../scripts/managers/GameManager';
import { EditorArrow } from './EditorArrow';
import { instantiate } from 'cc';
import { EditorArrowExplorerItem } from './EditorArrowExplorerItem';
import { BindDragWithLimited } from '../../../../scripts/libs/rxjs/cc3/BindNode';
import { lm } from '../../LobbyManager';
import { UITransform } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('EditorArrowExplorer')
export class EditorArrowExplorer extends BaseView {

    editorStageView: EditorStageView = null;

    @property(Node)
    container: Node = null;

    @property(Prefab)
    itemPrefab: Prefab = null;

    useObserves() {
        return [
            gm.arrowsInfoRefreshCommand.subscribe(this.refresh.bind(this)),
        ];
    }

    start() {
        BindDragWithLimited(this.node, lm.uiRoot.camera, () => {
            let size = this.node.parent.getComponent(UITransform).contentSize;
            return { x: [-size.width / 2, size.width / 2], y: [-size.height / 2, size.height / 2] }
        }).subscribe(_ => {
            if (_.type == 'touch-start') {
                this.node.setSiblingIndex(-1);
            }
        }).addTo(this.node);
    }

    refresh() {
        this.container.destroyAllChildren();
        if (this.editorStageView) {
            if (this.editorStageView.arrowMap != null) {
                let list: EditorArrow[] = [];
                for (let [arrowId, editorArrow] of this.editorStageView.arrowMap) {
                    list.push(editorArrow);
                }

                // TODO: 排序
                list.sort((a, b) => {
                    return b.node.getSiblingIndex() - a.node.getSiblingIndex();
                });

                for (let i = 0; i < list.length; i++) {
                    let editorArrow = list[i];
                    let itemNode = instantiate(this.itemPrefab);
                    let item = itemNode.getComponent(EditorArrowExplorerItem);
                    item.editorStageView = this.editorStageView;
                    item.editorArrow.value = editorArrow;
                    itemNode.setParent(this.container);
                }
            }
        }
    }
}

